package es.xpt.ysf.commons.jcr;

import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.media.jai.Interpolation;
import javax.media.jai.JAI;

public class ImageWrapper {

	public static File getFile(String uuid, float width, float height) {
		return new File(System.getProperty("java.io.tmpdir") + "/" + uuid + "#" + (int)width + "#" + (int)height + ".travelIOimg");
	}

	public static FileInputStream convertToFormatRatio(InputStream is, String fileName, String uuid, 
				float width, float height) throws IOException {
		File file = getFile(uuid, width, height	);
		
		// Can have length 0 if there was an error on previous run.
		if (!file.exists() || file.length() == 0 ) {
			RenderedImage image = ImageIO.read(is);
			float xRatio = width / image.getWidth();
			float yRatio = height / image.getHeight();
			String format = fileName.substring(fileName.lastIndexOf('.')+1);
			float ratio;
			if ( xRatio>0 && yRatio>0)
				ratio = Math.min(xRatio, yRatio);
			else 
				ratio = xRatio + yRatio;
				
			image = resize(image, Math.min(1.0F, ratio));
//			-Dcom.sun.media.jai.disableMediaLib=true
			
			ImageIO.write(image, format, file);
		} 
		return new FileInputStream(file);		
	}

	private static RenderedImage resize(RenderedImage image, float ratio) {
		ParameterBlock pb = new ParameterBlock();
		pb.addSource(image);
		pb.add(ratio);
		pb.add(ratio);
		pb.add(0.0F);
		pb.add(0.0F);
		pb.add(Interpolation.getInstance(Interpolation.INTERP_BILINEAR));
		return JAI.create("scale", pb);
	}
	
//	public static void main (String[] args ) throws IOException {
//		FileInputStream is = new FileInputStream(new File("D:/00-development/01-travelio/deployment/deploy/travelio.ear/boa3000.war/img/visor/foto2.jpg"));
//		ImageWrapper.convertToFormatRatio(is, 
//				"D:/00-development/01-travelio/deployment/deploy/travelio.ear/boa3000.war/img/visor/foto2.jpg",
//				"33",
//				300, 300);
//	}

}
